package spring.config;

import com.mysql.jdbc.Driver;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;
import spring.service.HelloWorld;
import spring.service.HelloWorldImpl;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
public class AppConfig {

    @Bean(name="helloBean")
    public HelloWorld helloWorld(){
        return new HelloWorldImpl();
    }

    @Bean(name="dataSource")
    public DataSource dataSource(){
        try {
            SimpleDriverDataSource driverDataSource=new SimpleDriverDataSource();
            driverDataSource.setUsername("root");
            driverDataSource.setPassword("123456");
            driverDataSource.setDriver(new Driver());
            driverDataSource.setUrl("jdbc:mysql://119.29.194.44:3306/douban");
            return driverDataSource;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Bean(name="sqlSessionFactoryBean")
    public SqlSessionFactoryBean sqlSessionFactoryBean(){
        SqlSessionFactoryBean factoryBean=new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        factoryBean.setConfigLocation(new ClassPathResource("classpath:mybatis-conf.xml"));
        return factoryBean;
    }

    @Bean(name="sqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(){
        try {
            SqlSessionTemplate template=new SqlSessionTemplate(sqlSessionFactoryBean().getObject());
            return template;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
